<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select
              v-model="selCateId"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="fliterArtCate" type="primary" size="small"
              >筛选</el-button
            >
            <el-button @click="resetArtList" type="info" size="small"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          type="primary"
          size="small"
          class="btn-pub"
          @click="pubVisible = true"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%">
        <el-table-column prop="title" label="文章标题" width="180">
          <template v-slot="scope">
            <el-link @click="showDetail(scope.row.id)" type="primary">{{
              scope.row.title
            }}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="cate_name" label="分类" width="180">
        </el-table-column>
        <el-table-column prop="pub_date" label="发表时间">
          <template v-slot="scope">
            <!-- 作用域插槽可以获取到当前行的时间 -->
            {{ formatDate(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态"> </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button @click="remove(scope.row.id)" size="mini" type="danger"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <!-- :current-page="currentPage4" :当前页 -->
      <!-- :page-siez="100" :页面大小 -->
      <!-- :page-sizes="[100,200,300,400]" :页面大小设置选项: n条/页 -->
      <!-- layout="total,sizes,prev,pager,next,jumpers" :设置分页组件的布局 -->
      <!-- :total="400" :数据的总量,发请求获取的 -->
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 关闭dialog -->
    <el-dialog
      @closed="dialogClose"
      fullscreen
      title="提示"
      :visible.sync="pubVisible"
      :before-close="beforeCloseHandler"
    >
      <el-form
        :model="artForm"
        :rules="artRules"
        ref="artForm"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model.trim="artForm.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>

        <el-form-item label="文章分类" prop="cate_id">
          <el-select
            @change="$refs.artForm.clearValidate('cate_id')"
            v-model="artForm.cate_id"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.cate_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <!-- 富文本编辑器的实现步骤 -->
          <!-- 1.装包:yarn add vue-quil-editor -->
          <!-- 2.将组件放到指定的区域 -->
          <!-- 3.将组件放到指定的区域 -->
          <!-- 4.双向绑定数据 -->
          <!-- 5.修改样式,min-height使用/deep/深度选择器 -->
          <quill-editor
            @change="$refs.artForm.clearValidate('content')"
            v-model="artForm.content"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img">
          <!-- <img
            v-if="artForm.cover_img"
            :src="artForm.cover_img"
            class="cover-img"
            alt=""
          /> -->
          <!-- v-else -->
          <img
            @change="$refs.artForm.clearValidate('cover_img')"
            :src="coverPreview"
            class="cover-img"
            ref="img"
          />
          <input
            v-if="pubVisible"
            type="file"
            style="display: none"
            accept="image/*"
            ref="iptFile"
            @change="uploadImg"
          />
          <br />
          <el-button type="text" @click="$refs.iptFile.click()"
            >+ 选择封面</el-button
          >
        </el-form-item>
        <el-form-item prop="state">
          <el-button @click="pubArticle('已发布')" type="primary"
            >发布</el-button
          >
          <el-button @click="pubArticle('草稿')" type="info"
            >存为草稿</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog
      title="文章预览"
      :visible.sync="detailsVisible"
      width="80%"
      :before-close="beforeCloseHandler"
    >
      <h1 class="title">{{ artDetail.title }}</h1>
      <div class="info">
        <span>作者:{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间:{{ formatDate(artDetail.pub_date) }}</span>
        <span>所属分类:{{ artDetail.cate_name }}</span>
        <span>状态:{{ artDetail.state }}</span>
      </div>
      <!-- 分割线 -->
      <el-divider></el-divider>
      <!-- 文章封面 -->
      <img
        :src="`http://www.liulongbin.top:3008${artDetail.cover_img}`"
        alt=""
      />
      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import defaultImg from '../../../assets/images/cover.jpg'
import dayjs from 'dayjs'
// import moment from 'moment'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 10,
        cate_id: '',
        state: ''
      },
      selCateId: '',
      state: '',
      pubVisible: false,
      artForm: {
        title: '',
        cate_id: null,
        content: '',
        cover_img: null,
        state: ''
      },
      coverPreview: defaultImg,
      cateList: [],
      artRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题必须是1~30个字符',
            trigger: 'blur'
          }
        ],
        // 不能提醒用户,但能做兜底校验
        cate_id: [
          { required: true, message: '请选择文章标题', trigger: 'change' }
        ],
        // 不能提醒用户,但能做兜底校验
        content: [
          { pattern: /^\S{1,}$/, message: '请输入文章内容', trigger: 'blur' }
        ],
        // 不能提醒用户,但能做兜底校验
        cover_img: [{ required: true, message: '请选择文章', trigger: 'blur' }]
      },
      artList: [],
      total: 0,
      artDetail: {},
      detailsVisible: false
    }
  },
  created () {
    // 获取分类列表
    this.getArtCate()
    // 获取文章列表
    this.getArtList()
  },
  methods: {
    // 关闭之前执行
    async beforeCloseHandler (done) {
      const res = await this.$confirm('关掉一定要关掉?????', '提示').catch(
        (e) => e
      )
      // console.log(res)
      if (res === 'confirm') done()
    },
    // 发送请求获取所有分类信息
    async getArtCate () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      if (res.code !== 0) return
      // console.log(res)
      this.cateList = res.data
    },
    // 上传图片
    uploadImg (e) {
      console.log(e.target.files)

      const file = e.target.files
      if (file.length === 0) {
        // 如果没选择图片,将cover_img清空
        this.artForm.cover_img = ''
        // this.$refs.img.setAttribute('src', defaultImg)
        this.coverPreview = defaultImg
      } else {
        // 如果选择了图片,将选择的图片赋值给cover_img
        this.artForm.cover_img = file[0]
        // files是blob对象的子对象所以可以直接上传file[0]对象
        // 将图片转换成url,给img标签显示
        const url = URL.createObjectURL(file[0])
        // console.log(url)
        // 给img标签设置src为url显示
        // this.$refs.img.setAttribute('src', url)
        this.coverPreview = url
      }
      // const reader = new FileReader()
      // // 将图片转换为base64格式
      // reader.readAsDataURL(file)
      // reader.onload = (e) => {
      //   console.log(e.target.result)
      //   this.artForm.cover_img = e.target.result
      // }
    },
    // 发布和草稿
    pubArticle (state) {
      // console.log(state)
      this.artForm.state = state
      this.$refs.artForm.validate(async (result) => {
        if (!result) return this.$message.error('请完善文章信息！')
        // console.log(this.artForm)
        const fd = new FormData()
        // for (const k in this.artForm) {
        //   // console.log(typeof k)
        //   fd.append(k, this.artForm[k])
        // }
        Object.keys(this.artForm).forEach((k) => fd.append(k, this.artForm[k]))
        const { data: res } = await this.$axios.post('/my/article/add', fd)
        // console.log(fd)
        if (res.code === 0) {
          // console.log(res)
          this.pubVisible = false
          this.getArtList()
        }
      })
    },
    // 关闭对话框
    dialogClose () {
      this.$refs.artForm.resetFields()
      this.coverPreview = defaultImg
    },
    // 渲染列表
    async getArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', {
        params: this.q
      })
      if (res.code === 0) {
        this.artList = res.data
        // console.log(res)
        // 获取到所有数据总数,赋值给data的total，分页组件中使用
        this.total = res.total
      }
    },
    // 格式化日期
    formatDate (date) {
      // 日期格式化
      // 1.装包yarn add dayjs
      // 2.引入import dayjs from 'dayjs'
      // 3.定义一个formatDate函数
      // 4.在函数中处理数据后返回
      // 5.在el-table-column中定义作用域插槽，调用日期处理函数并渲染结果
      // 调用dayjs函数传入日期字符串或对象
      // 调用format进行日期格式化,返回格式化后的日期
      return dayjs(date).format('YYYY-MM-DD hh:mm:ss')
    },
    // 监听pagesize变化
    sizeChangeHandle (val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getArtList()
    },
    // 监听pagenum变化
    currentChangeHandle (val) {
      // console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArtList()
    },
    // 删除列表数据
    async remove (id) {
      const res = await this.$confirm('确定要删除吗?', '提示').catch((e) => e)
      // console.log(res)
      if (res === 'confirm') {
        const { data: res } = await this.$axios.delete('/my/article/info', {
          params: { id }
        })
        if (res.code === 0) {
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          this.getArtList()
        }
      }
    },
    // 重置
    resetArtList () {
      this.q = {
        pagenum: 1,
        pagesize: 10,
        cate_id: '',
        state: ''
      }
      this.getArtList()
    },
    // 筛选
    fliterArtCate () {
      this.q.cate_id = this.selCateId
      this.q.state = this.state
      this.q.pagenum = 1
      this.getArtList()
    },
    // 显示详情
    async showDetail (id) {
      // 当用户点击时传入id发送请求
      const { data: res } = await this.$axios.get('/my/article/info', {
        params: { id }
      })
      // console.log(res)
      if (res.code === 0) {
        console.log(res)
        this.artDetail = res.data
        this.detailsVisible = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
.el-select {
  width: 100%;
}
// scoped帮我们做了两件事
// 1.给组件内所有元素加了v-data-hash
// 2.给所有的选择器加上了[v-data-hash]属性选择器
// 特点:如果组件内用了其他组件,scoped 只能加到根组件,再往深处就没了
// /deep/ : 深度样式
//  原理:使用[v-data-hash] .ql-editor 变成了属性+后代选择器,可以作用域更深层次的子级元素
/deep/ .ql-editor {
  min-height: 300px;
}
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.el-pagination {
  margin-top: 15px;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
